﻿<?php
include("mysql.php");

$tag = $_GET['tag'];

//check for archive space availability
$query = sprintf("SELECT value FROM settings WHERE property = 'archive_size'");
$result = mysql_query($query);

while($prop = mysql_fetch_array($result))
{
	
	$size = sprintf("SELECT * FROM images");
	$s_result = mysql_query($size);

	if(mysql_num_rows($s_result) >= $prop[0]){
		$delete = sprintf("DELETE FROM images WHERE isuser <> 1 LIMIT 1");
		mysql_query($delete);
	}
}

//check for duplicates, in case rename
/*$query = sprintf("SELECT * FROM images WHERE name = '%s'",
mysql_real_escape_string(basename( $_FILES['uploadedfile']['name'])));
$result = mysql_query($query);
while($result = mysql_fetch_array($result))
{
	$_FILES['uploadedfile']['name'] = 'a' . $_FILES['uploadedfile']['name'];
}*/

$final_message = "";
$target_path  = "./images/";

//upload image name
$query = sprintf("INSERT INTO images (name) VALUES ('%s')",
mysql_real_escape_string(basename( $_FILES['uploadedfile']['name'])));
$result = mysql_query($query);

$ukey = mysql_insert_id();
$key = "FEEDBACK_KEY_ID".$ukey;
// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
	$message  = 'Invalid query: ' . mysql_error() . "\n";
	$message .= 'Whole query: ' . $query;
	print(json_encode("FEEDBACK_START"));
	$output = "There was an error uploading the image, please try again!";

	$output = "FEEDBACK_KEY_UPLOAD".$output;
	print(json_encode($output));
	die($message);
}

//save the image as an hash (md5) file to prevent conflicts
//$imghash = md5($key.$_FILES['uploadedfile']['name']);
$imghash = $ukey;
$target_path = $target_path . basename($imghash).".jpg";

print(json_encode("FEEDBACK_START"));
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
	//$output =  "The file ".  basename( $_FILES['uploadedfile']['name'])." has been uploaded";
	
	$query = sprintf("UPDATE images SET tag = '%s' WHERE id = '%s'",
	mysql_real_escape_string($tag),mysql_real_escape_string($ukey));
	$result = mysql_query($query);
	
	$output =  "Your image has been uploaded";
	print(json_encode($key));
	$output = "FEEDBACK_KEY_UPLOAD".$output;
	print(json_encode($output));
} else{

	//upload image name
	$query = sprintf("DELETE * FROM images WHERE id = $key");
	mysql_query($query);
	mysql_close();

	$output = "There was an error uploading the image, please try again!";
	$output = "FEEDBACK_KEY_UPLOAD".$output;
	print(json_encode($output));
}
?>